//
//  WBStatusViewModel.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/8.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit

class WBStatusViewModel: NSObject {

    var status: WBStatus? {
        
        didSet {
            guard let currenStatus = status else {
                
                return
            }
            
            handleMbrankImage(mabrank: (currenStatus.user?.mbrank)!)
            handleVerifiedTypeImage(verifidrType: (currenStatus.user?.verified_type)!)
            hanleRetweetContent(status: currenStatus)
            reposts = hanleAttitudesCount(num: currenStatus.reposts_count)
            comments = hanleAttitudesCount(num: currenStatus.comments_count)
            attitudes = hanleAttitudesCount(num: currenStatus.attitudes_count)
            handleSoureContent(soure: currenStatus.source ?? "")
            originalAttributedText = handleAttributeText(text: currenStatus.text ?? "", isOrigisnal: true)
            if reposts == nil{
                
                reposts = "转发"
            }
            
            if comments == nil {
                
                comments = "评论"
            }
            
            if attitudes == nil {
                
                attitudes = "赞"
                
            }
            
            
            
            
        }
        
    }
    // 会员等级图片
    var mbrankImahe: UIImage?
    // 认证类型等级图片
    var verifiedTypeImage: UIImage?
    // 转发微博内容
    var retweetContent:String?
    // 转发数
    var reposts:String?
    // 评论数
    var comments: String?
    // 赞
    var attitudes: String?
    // 来源内容
    var sourceContent: String?
    // 只读计算数学, 每次使用都需要调用get方法
    var timeContent: String?{
        
        guard let createAt = status?.created_at  else {
            
            return nil
        }
        // 代码执行时间对象一定有值
        let dt = DateFormatter()
        
        if isThisYear(createAt: createAt) {
            // 今年
            // 创建日历对象
            let calendar = Calendar.current
            if calendar.isDateInToday(createAt) {
                // 今天
                let result = abs(createAt.timeIntervalSinceNow)
                if result < 60 {
                    
                    return "刚刚"
                } else if result < 3600 {
                    
                    let timeStr = result / 60
                    return "\(Int(timeStr))分钟前"
                } else {
                    
                    let timeStr = result / 3600
                    return "\(Int(timeStr))小时前"
                }
            } else if calendar.isDateInYesterday(createAt) {
                // 昨天
                dt.dateFormat = "昨天 HH:mm"
            } else {
                // 其他
                dt.dateFormat = "MM-dd HH:mm"
            }
        } else {
            
            // 不是今年
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        
        return dt.string(from: createAt)
        
    }
    
    // 原创微博富文本
    var originalAttributedText: NSAttributedString?
    // 转发微博富文本
    var retweetAttributedText: NSAttributedString?
    
    // 处理微博内容转成富文本
    private func handleAttributeText(text:String,isOrigisnal:Bool) ->NSAttributedString{
        
        // 把微博内容转成富文本
        let attributedText = NSMutableAttributedString(string: text)
        // 匹配微博内容中的表情描述
        let regularExpression = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: [])
        let matchresultArray = regularExpression.matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        
        var fontSize: CGFloat = 14
        if isOrigisnal == false {
            
            // 转发微博文字大小
            fontSize = 13
        }
        
        // 遍历匹配结果获取表情描述的范围
        // 需要从倒序遍历.这样匹配范围不会越界
        for matchResult in matchresultArray.reversed() {
            // 获取表情描述的范围
            let range = matchResult.range
            // 根据范围获取内容
            let chs = (text as NSString).substring(with: range)
            // 根据表情描述, 查找对应的表情模型
            if let emoticon = WBEmoticonTools.sharedTools.searchEmoticonWithChs(chs: chs) {
                
                let emoticonAttributeText = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: fontSize))
                // 替换指定范围的表情富文本
                attributedText.replaceCharacters(in: range, with: emoticonAttributeText)
            }
        }
        
        // 同一设置富文本的字体大小和文字文字颜色
        if isOrigisnal {
            
            attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: UIColor.darkGray], range: NSMakeRange(0, attributedText.length))
        } else {
            
            //  转发微博
            attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: UIColor.lightGray], range: NSMakeRange(0, attributedText.length))
        }
        
        return attributedText
    }
    
    // 判断是否是今年
    private func isThisYear(createAt: Date) ->Bool {
        
        let dt = DateFormatter()
        
        dt.dateFormat = "yyyy"
        // 获取微博的年份
        let createAtYeat = dt.string(from: createAt)
        // 获取当前时间
        let currenYeat = dt.string(from: Date())
        
        // 对比时间字符串是否相同
        return createAtYeat == currenYeat
        
    }
    
    private func hanleAttitudesCount(num:Int) -> String? {
    
        var repost = num
        
        var name: String?
        
        if repost % 10000 == 0 && repost != 0 {
            
            repost = repost / 10000
            
            name = String(format: "  %d万", repost)
            
            return name
        }
        
        if repost > 0 && repost < 10000 {
            
            name = "  \(repost)"
            
            return name
        }
        
        if repost > 10000 {
            
            let num = CGFloat(repost) / CGFloat(10000)
            
            let numOne = Int(num * 10) % 10
            
            if  numOne > 0 {
                
                name = String(format: "  %.1f万", num)
                
                return name
            }
            
            name = String(format: "  %.0f万", num)
            
            return name
        }
        
        if repost <= 0  {
            
            name = nil
        }
        
        return name
    }

    private func hanleRetweetContent(status:WBStatus) {
        
        if status.retweeted_status != nil {
            
            if let name = status.retweeted_status?.user?.screen_name,let text = status.retweeted_status?.text {
                
                retweetContent = "@\(name):\(text)"
                
                retweetAttributedText = handleAttributeText(text: retweetContent!, isOrigisnal: false)
            }
        }
        
    }
    
    private func handleMbrankImage(mabrank: Int) {
        
        if mabrank >= 1 && mabrank <= 6 {
            
            mbrankImahe = UIImage(named: "common_icon_membership_level\(mabrank)")
            
        }
        
    }
    private func handleVerifiedTypeImage(verifidrType: Int) {
        
        switch verifidrType {
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
        }
        
    }
    // 处理来源数据
    private func handleSoureContent(soure: String) {
        
        if let strarRange = soure.range(of: "\">"),let endRange = soure.range(of: "</") {
            // 获取指定范围的最大光标
            let strartIndex = strarRange.upperBound
            // 获取指定范围的最小光标
            let endIndex = endRange.lowerBound
            // 根据范围获取字符串
            let result = soure.substring(with: strartIndex..<endIndex)
            
            sourceContent = "来自: " + result
        }
        
    }
}
